# -*- coding: utf-8 -*-
"""
日志管理模块
"""

import sys
from typing import Optional
from pathlib import Path


try:
    from loguru import logger as _loguru_logger
    LOGGER = _loguru_logger
except Exception:
    # 简化版日志器
    class _SimpleLogger:
        def info(self, msg: str):
            print(f"[INFO] {msg}")

        def warning(self, msg: str):
            print(f"[WARN] {msg}", file=sys.stderr)

        def error(self, msg: str):
            print(f"[ERROR] {msg}", file=sys.stderr)

        def debug(self, msg: str):
            print(f"[DEBUG] {msg}")

    LOGGER = _SimpleLogger()


def setup_logger(
    log_dir: Optional[Path] = None,
    level: str = "INFO",
    rotation: str = "10 MB",
) -> None:
    """
    设置日志配置

    Args:
        log_dir: 日志目录
        level: 日志级别
        rotation: 日志轮转配置
    """
    # 移除默认控制台输出
    try:
        LOGGER.remove()
    except Exception:
        pass

    # 添加控制台输出
    try:
        LOGGER.add(
            sys.stdout,
            level=level,
            format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        )
    except Exception:
        # 简化版日志器
        pass

    # 添加文件输出
    if log_dir:
        log_dir = Path(log_dir)
        log_dir.mkdir(parents=True, exist_ok=True)

        try:
            LOGGER.add(
                log_dir / "app.log",
                level=level,
                rotation=rotation,
                retention="30 days",
                encoding="utf-8",
                format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
            )
        except Exception:
            pass
